<!--
 * @Author: Wanko
 * @Date: 2024-02-01 19:39:11
 * @LastEditors: Wanko
 * @LastEditTime: 2024-02-04 10:03:47
 * @Description: 
-->
<template>
  <div class="h-screen">
    <div class="flex-center">
      <el-input class="ml" v-model="assignNumber" placeholder="指定数量"></el-input>
      <el-button @click="getText">生成</el-button>
    </div>

    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 100%; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
    <el-dialog v-model="dialogVisible" title="卡片" width="50%">
      <div class="card-text" ref="cardText">
        <p v-for="(i, index) in list" :key="index">{{ i }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="onSwitch"> 换一个 </el-button>
          <el-button type="primary" @click="onCopy"> 复制 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage } from 'element-plus'
export default {
  components: { Editor, Toolbar },

  setup() {
    const dialogVisible = ref(false)
    const list = ref([])
    const assignNumber = ref(30)
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('')

    // // 模拟 ajax 异步获取内容
    // onMounted(() => {
    //     setTimeout(() => {
    //         valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
    //     }, 1500)
    // })

    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    let result, length

    const getText = () => {
      const editor = editorRef.value
      const fileContent = editor.getHtml()

      console.log(processString(fileContent))
      result = processString(fileContent)

      length = result.length
      if (!length) return
      console.log(result, length)
      // list.value = result
      // dialogVisible.value = true
      onGenerate(assignNumber.value)
      // const paragraphs = fileContent.split('\n\n') // 根据空行分割段落
      // console.log('段落数组:', paragraphs)

      // this.content = paragraphs.map((i) => {
      //   return {
      //     content: i
      //   }
      // })
    }
    const getRandomUniqueNumbers = (min, max, count) => {
      if (count > max - min + 1) {
        throw new Error('Count must be less than or equal to the range of numbers.')
      }

      const uniqueNumbers = new Set()

      while (uniqueNumbers.size < count) {
        const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min
        uniqueNumbers.add(randomNumber)
      }

      return Array.from(uniqueNumbers)
    }
    const onSwitch = () => {
      onGenerate(assignNumber.value)
    }

  
    const onGenerate = (number) => {
      const maxLength = length - 1
      const randomNumbers = getRandomUniqueNumbers(0, maxLength, number)

      const _list = randomNumbers.map((i, index) => {
        return `${index + 1}、${result[i]}`
      })

      list.value = _list
      dialogVisible.value = true
    }

    function processString(inputString) {
      // 使用正则表达式匹配 <p> 和 </p> 之间包含的纯文本内容，去掉任意位置的数字，保留标签里的文字
      // const regex = /<p>(.*?)<\/p>/g
      const regex = /<p(?:\s[^>]*)?>(.*?)<\/p>/g

      let match
      const result = []

      // 使用循环查找所有匹配项
      while ((match = regex.exec(inputString)) !== null) {
        // 提取 <p> 和 </p> 之间的纯文本内容，去掉标签、数字和、
        const content = match[1]
          .replace(/<[^>]+>/g, '')
          .replace(/\d+[\.、，]?/g, '') 
          .trim()
        console.log(content);
        if (content !== '') {
          result.push(`${content}`)
        }
      }
      
      return result
    }

    const cardText = ref(null)

    const onCopy = () => {
      const textToCopy = cardText.value.innerText

      const tempTextarea = document.createElement('textarea')
      tempTextarea.value = textToCopy
      onMounted(() => {
        cardText.value = document.querySelector('.card-text')
      })

      document.body.appendChild(tempTextarea)
      tempTextarea.select()
      document.execCommand('copy')
      document.body.removeChild(tempTextarea)
      ElMessage.success('文本已成功复制到剪贴板！')
    }
    const copyAllPTagsText = (parentElementId) => {
      // 获取父元素
      const parentElement = document.querySelector(parentElementId)

      // 获取所有 <p> 标签
      const pTags = parentElement.getElementsByTagName('p')

      // 创建一个文本区域用于保存文本内容
      const textarea = document.createElement('textarea')
      let copiedText = ''

      // 遍历 <p> 标签并将文本内容添加到 copiedText
      for (let i = 0; i < pTags.length; i++) {
        copiedText += pTags[i].textContent + '\n'
      }

      // 将文本内容设置到文本区域
      textarea.value = copiedText

      // 将文本区域添加到页面以便选择文本
      document.body.appendChild(textarea)

      // 选择文本并复制到剪贴板
      textarea.select()
      try {
        const successful = document.execCommand('copy')
        if (successful) {
          this.$message.success('文本已成功复制到剪贴板！')
        } else {
          alert('复制失败，请手动复制文本。')
        }
      } catch (err) {
        alert('复制失败，请手动复制文本。')
      } finally {
        // 删除文本区域
        document.body.removeChild(textarea)
      }
    }
    return {
      onGenerate,
      list,
      dialogVisible,
      getText,
      editorRef,
      valueHtml,
      mode: 'simple', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      onCopy,
      onSwitch,
      assignNumber,
      cardText
    }
  }
}
</script>

<style lang="scss" scoped></style>
